import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button, FormControlLabel, Switch } from '@mui/material';
import "./Feeding.css"

const AddFeedingDialog = ({ open, onClose, fetchData }) => {
    const [amount, setAmount] = useState(0);
    const [feedingTime, setFeedingTime] = useState('');
    const [editFeedingTime, setEditFeedingTime] = useState(false);
    const [brand, setBrand] = useState('');
    const [size, setSize] = useState('');
    const [batch, setBatch] = useState('');
    const [populationFed, setPopulationFed] = useState('');
    const [populations, setPopulations] = useState([]);

    useEffect(() => {
        fetchPopulations();
        setFeedingTime(formatToLocalDatetime(new Date()));
    }, []);

    const fetchPopulations = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/population`, { headers });
            setPopulations(response.data.populations);
        } catch (error) {
            console.error('Error fetching populations:', error);
        }
    };


    const addFeeding = async () => {
        try {
            const newFeeding = {
                "amount": amount,
                "feeding_time": feedingTime,
                "food_brand": brand,
                "food_size": size,
                "food_batch": batch,
                "id_population": populationFed,
            };
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            await axios.post(`${process.env.REACT_APP_API_BASE_URL}/feeding`, newFeeding, { headers });
            fetchData();
            onClose();
        } catch (error) {
            console.error('Error adding new feeding:', error);
        }
    };

    const handlePopulationChange = (event) => {
        setPopulationFed(event.target.value);
    };

    const handleBrandChange = (event) => {
        setBrand(event.target.value);
    };

    const handleInputChangeAmount = (event) => {
        setAmount(event.target.value);
    };

    const handleInputFeedingTime = (event) => {
        setFeedingTime(event.target.value);
    };

    const handleSizeChange = (event) => {
        setSize(event.target.value);
    };

    const handleBatchChange = (event) => {
        setBatch(event.target.value);
    };

    const toggleEditFeedingTime = () => {
        setEditFeedingTime(!editFeedingTime);
    };

    const formatToLocalDatetime = (date) => {
        const tzOffset = date.getTimezoneOffset() * 60000; // offset in milliseconds
        const localISOTime = new Date(date - tzOffset).toISOString().slice(0, 16);
        return localISOTime;
    };

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle sx={{
                                        fontFamily: 'Montserrat', fontWeight: 'bolder'
                                }}>Добавить новые данные</DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                    <div style={{ display: 'grid', gridTemplateColumns: "1.55fr 0.5fr 1fr", gap: '200px 20px' }}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={editFeedingTime}
                                        onChange={toggleEditFeedingTime}
                                    />
                                }
                                label="Хотите уточнить время кормления?"
                                sx={{
                                    '& .MuiFormControlLabel-label': {
                                        fontFamily: 'Montserrat', fontWeight: 'bolder',
                                    }
                                }}
                            />
                            <label>Время кормления</label>
                                <input
                                className='input-form-table'
                                    type="datetime-local"
                                    time
                                    value={feedingTime}
                                    onChange={handleInputFeedingTime}
                                    style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                    disabled={!editFeedingTime}
                                />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Популяция</label>
                            <select
                                value={populationFed}
                                onChange={handlePopulationChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                <option key={-1} value="">Выберите популяцию</option>
                                {populations.map(population => (
                                    <option key={population.pid} value={population.pid}>{population.code+" "+population.pname}</option>
                                ))}
                            </select>
                            <label>Количество корма</label>
                            <input
                            className='input-form-table'
                                type="number"
                                value={amount}
                                onChange={handleInputChangeAmount}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>                            <label>Марка</label>
                            <input
                            className='input-form-table'
                                type="text"
                                value={brand}
                                onChange={handleBrandChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Размер</label>
                            <input
                            className='input-form-table'
                                type="text"
                                value={size}
                                onChange={handleSizeChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Партия</label>
                            <input
                            className='input-form-table'
                                type="text"
                                value={batch}
                                onChange={handleBatchChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                        </div>
                        <Button onClick={addFeeding} sx={{ margin: 3, width: '50%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                            Сохранить
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
};

export default AddFeedingDialog;
